package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.aliyun.GreeTextScan;
import com.heima.aliyun.GreenImageScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    AdChannelMapper adChannelMapper;

    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    GreenImageScan greenImageScan;

    @Autowired
    AdSensitiveMapper sensitiveMapper;

    @Autowired
    ArticleFeign articleFeign;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Override
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //1.参数校验
        if (wmNewsId == null) {
            //打印日志
            log.error("当前的审核id空");
            //抛出异常
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            //结束当前程序
            return;
        }
        //2.根据文章id查询文章
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null) {
            //打印日志
            log.error("当前数据为空");
            //抛出异常
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            //结束当前程序
            return;
        }
        //3.文章状态=4 人工审核通过，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews);
            //结束当前程序
            return;
        }
        //4 文章状态=8 审核通过 但是发布时间小于等于当前时间，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews);
            //结束当前程序
            return;
        }
        //5 文章状态=1 待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //抽取文章内容种的文本和图片
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            // 5.1 自管理敏感词审核(审核成功true， 审核失败返回false且修改文章的状态)
            boolean isSensitiveScan = handleSensitive((String) contentAndImagesResult.get("content"), wmNews);
            if (!isSensitiveScan) return;
            // 5.2 阿里云审核文本内容(审核成功true， 审核失败返回false且修改文章的状态)
            boolean isTextScan = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!isTextScan) return;
            // 5.3 阿里云图片审核(审核成功true， 审核失败返回false且修改文章的状态)
            boolean isImageScan = handleImagesScan((List) contentAndImagesResult.get("images"), wmNews);
            if (!isImageScan) return;
            // 5.4 判断文章发布时间大于当前时间，修改状态8
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "文章审核通过待发布");
            }
        }


        // 6 保存文章相关数据
        saveAppArticle(wmNews);
        //TODO 7 同步索引库
    }

    /**
     * 阿里云-图片审核(审核成功true， 审核失败返回false且修改文章的状态)
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        //设置初始值
        boolean flag = true;
        // 图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        //检验图片
        try {
            Map map = greenImageScan.imageUrlScan(images);

            if (map.get("suggestion").equals("block")) { // 审核失败
                flag = false;
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章图片违规");
            }

            if (map.get("suggestion").equals("review")) {
                flag = false;
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章需要人工审核");
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            log.error("aliyun handleImagesScan is error,EX:{}, wmNewsId:{} ",e, wmNews.getId());
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章审核失败转入人工审核");
        }


        return flag;
    }

    /**
     * 阿里云-文本内容审核(审核成功true， 审核失败返回false且修改文章的状态)
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        //设置初始值
        boolean flag = true;
        //判断文章长度
        if (content.length() > 10000) {
            flag = false;
            log.error("文本长度过长");
            return flag;
        }
        //检查文章内容
        try {
            Map<String, String> map = greeTextScan.greeTextScan(content);
            //失败
            if (map.get("suggestion").equals("block")) { // 审核失败
                flag = false;
                updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章内容中包含敏感词");
            }

            if (map.get("suggestion").equals("review")) {
                flag = false;
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章需要人工审核");
            }

        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            log.error("aliyun handleTextScan is error,EX:{}, wmNewsId:{} ",e, wmNews.getId());
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章审核失败转入人工审核");
        }


        return flag;
    }

    /**
     * 修改文章状态
     * @param wmNews
     * @param code
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short code, String reason) {
        wmNews.setStatus(code);
        wmNews.setReason(reason);
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (result.getCode() != 0) { // 执行失败
            CustException.cust(AppHttpCodeEnum.WEMEDIA_UPDATE_ERROR);
        }
    }

    /**
     * 自管理敏感词审核(审核成功true， 审核失败返回false且修改文章的状态)
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        // DFA
        // 1 敏感词词库
        List<String> sensitive = sensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(sensitive);

        //2 匹配
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) { // 文章内容包含敏感词
            log.info("文章内容包含敏感词" + map);
            flag = false;

            // 修改文章状态
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文章内容包含敏感词"+map );

        }

        return flag;
    }

    /**
     * 抽取文章的 文本和图片（包含封面的图片[不带前缀]）
     * @param wmNews
     * @return Map 图片带前缀
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //1.获取文章内容并转换对象
        String content = wmNews.getContent();
        if (StringUtils.isBlank(content) || content.length() > 10000) {
            //结束程序
            return null;
        }
        List<Map> contentList = JSON.parseArray(content, Map.class);
        //2.解析内容文本 Stream流优化
        String contents = contentList.stream()
                .filter(x -> x.get("type").equals("text"))
                .map(y -> y.get("value").toString())
                .collect(Collectors.joining("_hmtt_"));
        //获取文章标题 参与审核
        contents = wmNews.getTitle() + "_hmtt_" + contents;
        //3.解析内容图片
        List<String> images = contentList.stream()
                .filter(x -> x.get("type").equals("image"))
                .map(y -> y.get("value").toString())
                .collect(Collectors.toList());
        //4.处理封面前缀
        String imageCover = wmNews.getImages();
        if (StringUtils.isNotBlank(imageCover)){
            //添加到内容 图片列表
            images.addAll(Stream.of(imageCover.split(","))
                    .map(x->webSite+x)
                    .collect(Collectors.toList()));
        }
        //5.封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content",contents);
        resultMap.put("images",images);
        return resultMap;
    }

    /**
     * 保存APP端文章相关数据
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        // 保存成功 文章ID
        ResponseResult result = saveArticle(wmNews);

        if (result.getCode() != 0) {
            throw new RuntimeException("文章审核保存app文章失败");
        }

        // data 设置文章ID
        wmNews.setArticleId((Long) result.getData());
        // 更新自媒体文章状态为9
        updateWmNews(wmNews, WmNews.Status.PUBLISHED.getCode(), "已发布");
    }

    /**
     * 执行保存文章（三张表）
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticle(WmNews wmNews) {
        //1 封装数据 dto
        ArticleDto articleDto = new ArticleDto();

        BeanUtils.copyProperties(wmNews, articleDto);
        articleDto.setId(null);
        if (wmNews.getArticleId()!=null) {
            articleDto.setId( wmNews.getArticleId() );
        }
        // 布局
        articleDto.setLayout(wmNews.getType());
        articleDto.setFlag((byte) 0);

        //2 设置频道
        if (wmNews.getChannelId() != null) {
            articleDto.setChannelId(wmNews.getChannelId());
            AdChannel channel = adChannelMapper.selectById(wmNews.getChannelId());
            if (channel != null) {
                articleDto.setChannelName(channel.getName());
            }
        }

        //3 设置作者信息
        // 查wm_user 状态
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId());
        if (wmUser == null || wmUser.getStatus().intValue() != 9) { // 非法用户
            CustException.cust(AppHttpCodeEnum.ADMIN_ADUSER_ISNTOEXIT_ERROR);
        }
        if (StringUtils.isNotBlank(wmUser.getName())) {
            // 自媒体名称不能修改
            articleDto.setAuthorName(wmUser.getName());
            // 作者id 尽量减少远程调用
        }

        //4 文章内容
        articleDto.setContent(wmNews.getContent());

        // 发起远程调用 保存 三张表数据, 返回值必须携带文章id
        return articleFeign.saveArticle(articleDto);
    }
}
